package com.quran.viewcontrollers;


import java.io.File;
import java.net.UnknownHostException;
import java.util.List;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.bappi.utils.AlertUtils;
import com.bappi.utils.Constants;
import com.bappi.utils.FileUtils;
import com.bappi.utils.MediaPlayerUtils;
import com.bappi.utils.Utils;
import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.markupartist.android.widget.ActionBar;
import com.tos.quran.R;

public class Tab2Controller extends AbstractViewController {

	private List<String[]> versesInfos;
	private VersesListAdapter versesListAdapter;
	private View listViewContainer;
	private ListView listView;
	private TextView messageView;

	private String langCode;

	private boolean isPaused;
	private View buttonContainer, bottomHelperLayout;
	private ImageButton playPauseButton, prevButton, nextButton;

	// private HashMap<String, String> hashRender;
	private ActionBar actionBar;
	private int currentPlayingIndex;
	private boolean isNoTranslateSelected;

	private OnCompletionListener onCompletionListener = new OnCompletionListener() {

		public void onCompletion(MediaPlayer mp) {
			try {
				currentPlayingIndex = -1;
				hideButtonPanel();
				versesListAdapter.notifyDataSetChanged();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};
	
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		if (Constants.KEY_BOOKMARK_CHANGED_CODE.equals(key)) {
			manageView();
		}
	};


	public Tab2Controller(AbstractTabRootManager tabRootManager) {
		super(tabRootManager, R.layout.tab2_view);
		try {
			
			langCode = getSharedPreferences().getString(
					Constants.KEY_SELECTED_TRANS_CODE,
					Constants.LANG_CODE_DEFAULT);
			isNoTranslateSelected = Constants.LANG_CODE_NONE.equals(langCode);
			

			actionBar = (ActionBar) findViewById(R.id.actionbar);
			// hashRender = new HashMap<String, String>();

			

			currentPlayingIndex = -1;
			actionBar.setTitle(getString(R.string.text_tab2));

			listView = (ListView) findViewById(R.id.list_view);
			listViewContainer = findViewById(R.id.list_view_container);
			messageView = (TextView) findViewById(R.id.message_view);

			buttonContainer = findViewById(R.id.bottom_layout);
			bottomHelperLayout = findViewById(R.id.bottom_helper_layout);
			playPauseButton = (ImageButton) findViewById(R.id.play_pause_button);
			prevButton = (ImageButton) findViewById(R.id.prev_button);
			nextButton = (ImageButton) findViewById(R.id.next_button);
			playPauseButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (isPaused) {
							MediaPlayerUtils.play();
							isPaused = false;
						} else {
							MediaPlayerUtils.pause();
							isPaused = true;
						}
						manageButtons();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			nextButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex < (versesInfos.size() - 1)) {
							currentPlayingIndex++;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			prevButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					try {
						if (currentPlayingIndex > 0) {
							currentPlayingIndex--;
							play();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			versesListAdapter = new VersesListAdapter();
			listView.setAdapter(versesListAdapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				public void onItemClick(AdapterView<?> av, View v,
						int position, long arg) {
					versesClicked(position);
				}
			});
			listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

				public boolean onItemLongClick(AdapterView<?> av, View v,
						int position, long arg) {
					versesLongClicked(position);
					return true;
				}
			});
			manageView();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void manageView() {
		try {
			new AsyncTask<String, String, String>() {
				private AlertUtils.SpinnerProgressDialog spinnerProgressDialog;

				@Override
				protected void onPreExecute() {
					try {
						messageView.setVisibility(View.INVISIBLE);
						listViewContainer.setVisibility(View.INVISIBLE);
						spinnerProgressDialog = AlertUtils.getProgressDialog(
								getActivity(),
								getString(R.string.dialog_default_title),
								getString(R.string.please_wait));
						spinnerProgressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						
						versesInfos = getActivity().getDatabaseAccessor()
								.getBookmarkVerses(langCode);

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						versesListAdapter.notifyDataSetChanged();
						if (versesInfos.size() > 0) {
							listViewContainer.setVisibility(View.VISIBLE);
						} else {
							messageView.setVisibility(View.VISIBLE);
						}
						spinnerProgressDialog.dismiss();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onDestroy() {
		try {
			MediaPlayerUtils.stopPlaying();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	public class VersesListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public VersesListAdapter() {
			mInflater = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return versesInfos == null ? 0 : versesInfos.size();
		}

		public Object getItem(int arg0) {
			Object ret = null;
			if (versesInfos != null && versesInfos.size() > arg0) {
				ret = versesInfos.get(arg0);
			}
			return ret;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			try {
				ViewHolder holder;
				if (convertView == null) {
					convertView = mInflater.inflate(
							R.layout.bookmark_list_content, null);
					holder = new ViewHolder();
					holder.mainContainer = convertView
							.findViewById(R.id.main_container);

					holder.suraNameEn = (TextView) convertView
							.findViewById(R.id.view_sura_name_eng);
					holder.suraNameAr = (TextView) convertView
							.findViewById(R.id.view_sura_name_ara);
					holder.verseNo = (TextView) convertView
							.findViewById(R.id.view_verse_no);

					holder.versesAra = (TextView) convertView
							.findViewById(R.id.view_verses_ara);
//					holder.versesAra.setLineSpacing(Constants.SPACING_FACTOR
//							* holder.versesAra.getPaint().getTextSize(), 1);
					holder.versesOthers = (TextView) convertView
							.findViewById(R.id.view_verses_others);

					if (isNoTranslateSelected) {
						holder.versesOthers.setVisibility(View.GONE);
					} else {
						holder.versesOthers.setVisibility(View.VISIBLE);
//						if (Constants.LANG_CODE_BENGALI.equals(langCode)) {
//							holder.versesOthers.setLineSpacing(6, 1);
//							holder.versesOthers.setTypeface(bengaliTypeface);
//						} else if (Constants.LANG_CODE_PERSIAN.equals(langCode)) {
//							holder.versesOthers.setTypeface(arabicTypeface);
//							holder.versesOthers.setTextSize(
//									TypedValue.COMPLEX_UNIT_PX,
//									holder.versesAra.getTextSize());
//							holder.versesOthers.setGravity(Gravity.RIGHT);
//						} else if (Constants.LANG_CODE_HINDI.equals(langCode)) {
//							holder.versesOthers.setTypeface(hindiTypeface);
//						}
					}
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
//				holder.versesAra.setSpecialChars(versesInfos.get(position)[2]);
				holder.versesAra.setText(versesInfos.get(position)[1]);
				if (!isNoTranslateSelected) {
					holder.versesOthers.setText(versesInfos.get(position)[3]);
				}
				holder.suraNameEn.setText(versesInfos.get(position)[6]);
				holder.suraNameAr.setText(versesInfos.get(position)[5]);
				holder.verseNo
						.setText("(" + versesInfos.get(position)[8] + ")");
				if (currentPlayingIndex == position) {
					holder.mainContainer.setBackgroundColor(0x44000000);
				} else {
					holder.mainContainer.setBackgroundColor(0x00000000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			View mainContainer;
			TextView suraNameEn;
			TextView suraNameAr;
			TextView verseNo;
			TextView versesAra;
			TextView versesOthers;
		}
	}

	private void versesLongClicked(final int position) {
		try {
			final Dialog dialog = new Dialog(getActivity());
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.verses_options);
			dialog.setCancelable(false);
			Button buttonReoveFromBookmark = (Button) dialog
					.findViewById(R.id.button_add_to_bookmark);
			Button buttonShare = (Button) dialog
					.findViewById(R.id.button_share);
			Button buttonCancel = (Button) dialog
					.findViewById(R.id.button_cancel);
			if (!Utils.isShareable(langCode)) {
				buttonShare.setVisibility(View.GONE);
			}
			buttonReoveFromBookmark
					.setText(getString(R.string.remove_this_verse_from_bookmard));
			buttonReoveFromBookmark
					.setOnClickListener(new View.OnClickListener() {

						public void onClick(View v) {
							dialog.dismiss();
							removeFromBookmark(position);
						}
					});
			buttonShare.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					dialog.dismiss();
					Intent sharingIntent = new Intent(Intent.ACTION_SEND);
					// sharingIntent.setType("text/html");
					sharingIntent.setType("text/plain");
					sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
							versesInfos.get(position)[3]);
					getActivity().startActivity(Intent.createChooser(sharingIntent,
							getString(R.string.sharing_intent_title)));
				}
			});
			buttonCancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void play() throws Exception {
		isPaused = false;
		manageButtons();
		showButtonPanel();
		versesListAdapter.notifyDataSetChanged();
		if ((currentPlayingIndex < listView.getFirstVisiblePosition())
				|| (currentPlayingIndex >= listView.getLastVisiblePosition())) {
			listView.setSelection(currentPlayingIndex);
		}

		MediaPlayerUtils.playFile(getActivity(), FileUtils.getFile(getActivity(),
				versesInfos.get(currentPlayingIndex)[4],
				String.format("%03d%03d.mp3", Integer.parseInt(versesInfos
						.get(currentPlayingIndex)[4]), Integer
						.parseInt(versesInfos.get(currentPlayingIndex)[8]))),
				onCompletionListener);
	}

	private void removeFromBookmark(final int position) {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;

				@Override
				protected void onPreExecute() {
					try {
						progressDialog = new ProgressDialog(getActivity());
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_SPINNER);
						progressDialog.setCancelable(true);
						progressDialog.setIndeterminate(true);
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					int versesId = Integer
							.parseInt(versesInfos.get(position)[0]);
					getActivity().getDatabaseAccessor().deleteFromBookmark(versesId);
					versesInfos.remove(position);
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						versesListAdapter.notifyDataSetChanged();
						progressDialog.dismiss();
						Utils.showAlertDialog(getActivity(),
								getString(R.string.removed_from_bookmark));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void versesClicked(final int position) {
		try {
			File file = FileUtils.getFile(getActivity(), versesInfos
					.get(position)[4], String.format("%03d%03d.mp3",
					Integer.parseInt(versesInfos.get(position)[4]),
					Integer.parseInt(versesInfos.get(position)[8])));
			if (file.exists() && file.isFile()) {
				currentPlayingIndex = position;
				play();
			} else {
				Utils.showAlertDialogYesNo(getActivity(),
						getString(R.string.message_download_conf),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								downloadFile(position);
							}
						}, new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadFile(final int position) {
		try {
			try {
				new AsyncTask<String, String, String>() {
					private String exception;
					private ProgressDialog progressDialog;

					protected void onPreExecute() {
						try {
							progressDialog = Utils
									.getProgressDialog(getActivity());
							progressDialog.show();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					protected String doInBackground(String... arg0) {
						try {
							FileUtils
									.downloadVerse(getActivity(),
											Constants.FILE_DOWNLOAD_URL,
											Integer.parseInt(versesInfos
													.get(position)[4]), Integer
													.parseInt(versesInfos
															.get(position)[8]));
						} catch (UnknownHostException uhe) {
							exception = getString(R.string.message_go_online);
							uhe.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
							exception = e.getLocalizedMessage();
						}
						return null;
					}

					protected void onPostExecute(String unused) {
						try {
							progressDialog.dismiss();
							if (exception != null) {
								Utils.showAlertDialog(getActivity(), exception);
							} else {
								currentPlayingIndex = position;
								play();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void manageButtons() {
		try {
			if (currentPlayingIndex > 0) {
				prevButton.setEnabled(true);
			} else {
				prevButton.setEnabled(false);
			}
			if (currentPlayingIndex < (versesInfos.size() - 1)) {
				nextButton.setEnabled(true);
			} else {
				nextButton.setEnabled(false);
			}
			if (isPaused) {
				playPauseButton.setImageResource(R.drawable.play);
			} else {
				playPauseButton.setImageResource(R.drawable.pause);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showButtonPanel() {
		try {
			if (buttonContainer.getVisibility() != View.VISIBLE) {

				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f,
						Animation.RELATIVE_TO_SELF, 0.0f);
				animation.setDuration(600);
				animation
						.setAnimationListener(new Animation.AnimationListener() {

							public void onAnimationStart(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationRepeat(Animation animation) {
								// TODO Auto-generated method stub

							}

							public void onAnimationEnd(Animation animation) {
								try {
									bottomHelperLayout.getLayoutParams().height = buttonContainer
											.getHeight();
									listView.requestLayout();
								} catch (Exception e) {
									e.printStackTrace();
								}

							}
						});
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void hideButtonPanel() {
		try {
			if (buttonContainer.getVisibility() == View.VISIBLE) {
				bottomHelperLayout.getLayoutParams().height = 0;
				Animation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 0.0f,
						Animation.RELATIVE_TO_SELF, 1.0f);
				animation.setDuration(600);
				buttonContainer.startAnimation(animation);
				buttonContainer.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
